package com.hmdp.interceptor;

import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: dupeng
 * @CreateTime: 2024-10-22  15:40
 * @Description: 登录拦截器
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //基于redis实现拦截
        return preHandleRedis(response);
    }

    /**
     * 基于session实现拦截
     * @param request
     * @return
     * @throws Exception
     */
    private boolean preHandleSession(HttpServletRequest request) throws Exception {
        //判断用户是否登录
        UserDTO user = (UserDTO) request.getSession().getAttribute("user");
        if (Objects.isNull(user)){
            throw new RuntimeException("请先登录");
        }

        //保存用户至ThreadLocal
        UserHolder.saveUser(user);

        //放行
        return true;
    }

    /**
     * 基于redis实现拦截
     * @param response
     * @return
     * @throws Exception
     */
    private boolean preHandleRedis(HttpServletResponse response) {
        // 判断是否需要拦截（ThreadLocal中是否有用户）
        UserDTO user = UserHolder.getUser();
        if (Objects.isNull(user)) {
            response.setStatus(401);
            return false;
        }
        //放行
        return true;
    }
}
